/**
 * 
 */
package edu.arizona.bio5.onto.util;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.io.RDFXMLOntologyFormat;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLLogicalAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import uk.ac.manchester.cs.util.SetUtils;

/**
 * Generates samples of a big ontology
 *
 * (c) Pavel Klinov
 *
 */
public class OntologySampler {

	public static void main(String... args) throws Exception {
		
		OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
		OWLOntology source = mgr.loadOntologyFromOntologyDocument(new File("eval/data/GO/go_daily-termdb.owl"));
		
		OntologyUtils.prepareForSyntacticModularity(source);
		
		generateSample(source, mgr, "eval/data/GO/GO_20K.owl", 20000);
		/*generateSample(source, mgr, "eval/CHEBI/CHEBI_10K.owl", 10000);
		generateSample(source, mgr, "eval/CHEBI/CHEBI_20K.owl", 20000);
		generateSample(source, mgr, "eval/CHEBI/CHEBI_30K.owl", 30000);
		generateSample(source, mgr, "eval/CHEBI/CHEBI_40K.owl", 40000);
		generateSample(source, mgr, "eval/CHEBI/CHEBI_50K.owl", 50000);*/
	}
	

	public static void generateSample(String sourceFile, String sampleFile, int size) throws Exception {
		
		OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
		OWLOntology source = mgr.loadOntologyFromOntologyDocument(new File(sourceFile));
		
		OntologyUtils.prepareForSyntacticModularity(source);
		generateSample(source, mgr, sampleFile, size);
	}
	
	public static void generateSample(OWLOntology source, OWLOntologyManager mgr, String sampleFile, int size) throws Exception {
		IRI sampleIRI = IRI.create(source.getOntologyID().getOntologyIRI().toString() + ".sample"); 
		Set<OWLAxiom> axioms = new HashSet<OWLAxiom>();
		Set<OWLLogicalAxiom> sourceAxioms = source.getLogicalAxioms();
		Set<OWLLogicalAxiom> sampleAxioms = SetUtils.pickRandomSubset(sourceAxioms, size); 
		
		axioms.addAll(sampleAxioms);
		mgr.saveOntology(mgr.createOntology(axioms, sampleIRI),  new RDFXMLOntologyFormat(), IRI.create(new File(sampleFile).toURI()));
	}	
}
